﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using EEA.SOACommerce.Shared.ServiceClients.Config;

namespace EEA.SOACommerce.Shared.ServiceClients
{
    public class ServiceClientBuilder
    {
        public static T Build<T>(ServiceClientConfiguration config)
        {

            ServiceBehaviorAttribute beh = new ServiceBehaviorAttribute();

            BasicHttpBinding binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = config.MaxReceivedMessageSize;
            binding.MaxBufferSize = config.MaxBufferSize;
            binding.ReaderQuotas.MaxArrayLength = config.MaxArrayLength;
            binding.ReaderQuotas.MaxDepth = config.MaxDepth;
            binding.ReaderQuotas.MaxBytesPerRead = config.MaxBytesPerRead;
            binding.ReaderQuotas.MaxStringContentLength = config.MaxStringContentLength;
            binding.CloseTimeout = new TimeSpan(0, config.TimeOutInMinute, 0);
            binding.OpenTimeout = new TimeSpan(0, config.TimeOutInMinute, 0);
            binding.ReceiveTimeout = new TimeSpan(0, config.TimeOutInMinute, 0);
            binding.SendTimeout = new TimeSpan(0, config.TimeOutInMinute, 0);

            EndpointAddress address = new EndpointAddress(config.Location);

            ChannelFactory<T> _channelFactory = new ChannelFactory<T>(binding, address);
            foreach (OperationDescription op in _channelFactory.Endpoint.Contract.Operations)
            {

                DataContractSerializerOperationBehavior dataContractBehavior =

                op.Behaviors[typeof(DataContractSerializerOperationBehavior)]

                as DataContractSerializerOperationBehavior;

                if (dataContractBehavior != null)
                {

                    dataContractBehavior.MaxItemsInObjectGraph = config.MaxItemsInObjectGraph;
                }

            }


            return _channelFactory.CreateChannel();

        }
    }
}
